import React, { useEffect, useState } from 'react';
import { message } from 'antd';
import moment from 'moment';
import useRefState from '@/pages/hooks/usehooks/useRefState';

// 参考地址: https://www.ruanyifeng.com/blog/2017/05/server-sent_events.html
export default function SSE() {
  const [messageList, setMessageList] = useRefState([]);
  const [, setRefresh] = useState(new Date());
  useEffect(() => {
    const source = new EventSource('http://10.10.42.70:8080/sse/data/push');
    source.onopen = function() {
      message.success('连接成功～');
    };

    source.onerror = function() {
      message.error('连接发生错误～');
    };

    source.addEventListener(
      'connecttime',
      function(event) {
        console.log(`连接时间: ${event.data}`);
      },
      false,
    );

    source.onmessage = function(event) {
      console.log('接受的数据:', event.data);
      setMessageList(prev => [
        { content: event.data, createTime: moment().format('YYYY-MM-DD HH:mm:ss') },
        ...prev,
      ]);
      setRefresh(new Date());
    };

    return () => {
      console.log('close');
      source.close();
    };
  }, []);
  return (
    <ul style={{ padding: 0 }}>
      {messageList.current.map(msg => (
        <ol key={msg.createTime} style={{ margin: 20, background: '#fff', padding: 10 }}>
          <span>
            <strong style={{ fontSize: 18 }}>内容：</strong>
            <span>{msg.content}</span>
          </span>
          <div style={{ color: '#ccc', textAlign: 'right', paddingRight: 10 }}>
            创建时间: {msg.createTime}
          </div>
        </ol>
      ))}
    </ul>
  );
}
